#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <string>
#include <unistd.h>
#include "InetAddr.hpp"
#include "Comm.hpp"
using namespace std;

void Usage(string proc)
{
    cerr << "Usage:" << proc << " ip  port" << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    string Serverip = argv[1];
    uint16_t Serverport = stoi(argv[2]);

    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cerr << "socket create error" << endl;
        exit(SOCKET_CREATE_ERR);
    }

    InetAddr addr(Serverport, Serverip);
    if (connect(sockfd, addr.Addr(), addr.Length()) != 0)
    {
        cerr << "connect error" << endl;
        exit(SOCKET_CONNECT_ERR);
    }
    cout << "connect" << addr.Tostring() << "success" << endl;

    while (true)
    {
        cout << "Please Enter# ";
        string line;
        getline(cin, line);
        ssize_t n = write(sockfd, line.c_str(), line.size());

        char buffer[1024];
        ssize_t m = read(sockfd, buffer, sizeof(buffer) - 1);
        if (m > 0)
        {
            buffer[m] = 0;
            cout << buffer << endl;
        }
    }

    return 0;
}